package two_to_two;

import java.io.OutputStream;
import java.net.Socket;

/**
 * @author Xu,
 * @data 2021/1/5，
 * @time 10:22
 */
public class Producers2 implements Runnable{
    private static long number;
    private static StringBuffer stringBuffer = new StringBuffer();
    public static int times = 500;

    public Producers2() {

    }


    /**
     * 获取随机生成的大于20亿的正整数；
     */
    public synchronized static long getRandom() {
        stringBuffer.append(String.valueOf(2 + (int) (Math.random() * 8)));
        for (int i = 1; i < 10; i++) {
            stringBuffer.append(String.valueOf((int) (Math.random() * 10)));
        }
        number = Long.parseLong(stringBuffer.toString());
        stringBuffer.setLength(0);
        return number;
    }

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        Producers2 p1 = new Producers2();
        Producers2 p2 = new Producers2();
        Thread t1 = new Thread(p1);
        Thread t2 = new Thread(p2);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        long end = System.currentTimeMillis();
        System.out.println("runtime: " + (end - start)/1000.0 + "s");
    }

    @Override
    public void run() {
        try{
            Socket socket;
            for (int i = 0; i < times; i++) {
                String host = "localhost";
                int port = 10303;
                socket = new Socket(host, port);
                String msg = "p";
                for(int j=0;j<1000;j++) {
                    msg += " " + getRandom();
                }
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(msg.getBytes("UTF-8"));
                outputStream.flush();
                socket.shutdownOutput();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
